import compose from './compose';
/*
export default function applyMiddleware(middleware){
    return function(createStore){
        return function(reducer){
            let store = createStore(reducer);
            let dispatch = () => {throw Error('现在还不能用！')};
            middleware = middleware(store);
            dispatch = middleware(store.dispatch);
            return {
                ...store
                , dispatch
            };
        }
    }
}
*/

//applyMiddleware(thunk, logger)(createStore)
/*
let logger = function (api: any) {//api
    return function (next: any) {//下一个中间件
        return function (action: any) {//派发的动作
            console.log('变更前的老状态2', api.getState());//store.dispatch
            next(action);//调用下一个中间件 store.dispatch
            console.log('变更后的新状态2', api.getState());
        }
    }
};
*/
//支持多个middleware
export default function applyMiddleware(...middlewares){ //之所以包三层，就是因为这里数量不固定
    //↓storeEnhancer
    return function(createStore){
        //↓storeEnhancerStoreCreator
        return function(reducer){
            let store = createStore(reducer);
            let dispatch = () => {throw Error('现在还不能用！')};
            let middlewareAPI = {
                getState: store.getState
                , dispatch: (...args) => dispatch(...args)
            };

            const chain = middlewares.map(middleware => middleware(middlewareAPI));
            dispatch = compose(...chain)(store.dispatch); //此时dispatch才可用
            //store.dispatch是logger2的参数(dispatch),logger2是logger1的参数(dispatch),logger1的运行结果就是let dispatch
            //而dispatch又是一个函数(即logger1中间件我们想要它执行的逻辑)，但之前每一层的参数都因为闭包保存了下来
            //这样派发时就会先进入logger1中间件然后logger2中间件然后从logger2中间件出，再从logger1中间件出
            return {
                ...store
                , dispatch // 狸猫换太子 重写dispatch
            };
        }
    }
}

